package com.sitech.portal.util.listener;

import com.sitech.BaseConst;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.*;

public class WebSessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();
        // 在application范围由一个HashSet集保存所有的session
        Map sessions = (Map) application.getAttribute("sessions");
        if (sessions == null) {
            synchronized (this) {
                sessions = (Map) application.getAttribute("sessions");
                if (sessions == null) {
                    sessions = Collections.synchronizedMap(new HashMap());
                    application.setAttribute("sessions", sessions);
                }
            }
        }

        TblSYS_LOGINMSG user = (TblSYS_LOGINMSG) session.getAttribute(BaseConst.SESSION_USER_KEY);
        if (user != null) {
            // 新创建的session均添加到HashSet集中
            sessions.put(user.getLOGIN_ID(), session);
        }

        // 可以在别处从application范围中取出sessions集合
        // 然后使用sessions.size()获取当前活动的session数，即为“在线人数”

        Set<HttpSession> sessionSet = (Set<HttpSession>) application.getAttribute("sessionSet");
        if (sessionSet == null) {
            synchronized (this) {
                sessionSet = (Set) application.getAttribute("sessionSet");
                if (sessionSet == null) {
                    sessionSet = Collections.synchronizedSet(new HashSet());
                    application.setAttribute("sessionSet", sessionSet);
                }
            }
        }
        sessionSet.add(session);
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();
        TblSYS_LOGINMSG user = (TblSYS_LOGINMSG) session.getAttribute(BaseConst.SESSION_USER_KEY);

        Map sessions = (Map) application.getAttribute("sessions");
        // 销毁的session均从HashSet集中移除
        if (sessions != null && user != null)
            sessions.remove(user.getLOGIN_ID());
        // 设置该用户的离线时间。
        // SYS_LOGINMSGDao logmsgDao = new SYS_LOGINMSGDao();
        // logmsgDao.setUserOutline(session.getId());
        Set<HttpSession> sessionSet = (Set<HttpSession>) application.getAttribute("sessionSet");
        if (sessionSet != null) {
            sessionSet.remove(session);
        }
    }
}

